package com.xiaolei.libraryktx

import com.google.gson.Gson
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext

/**
 * 启动一个协程
 */
inline fun launch(
        context: CoroutineContext = EmptyCoroutineContext,
        start: CoroutineStart = CoroutineStart.DEFAULT,
        noinline block: suspend CoroutineScope.() -> Unit
): Job?
{
    return try
    {
        GlobalScope.launch(context, start, block)
    } catch (e: Exception)
    {
        e.printStackTrace()
        null
    }
}

/**
 * 协程里的暂停
 */
suspend inline fun delay(timeMillis: Long)
{
    kotlinx.coroutines.delay(timeMillis)
}

/**
 * 协程丶同步
 */
fun <T> async(
        context: CoroutineContext = EmptyCoroutineContext,
        start: CoroutineStart = CoroutineStart.DEFAULT,
        block: suspend CoroutineScope.() -> T
) = GlobalScope.async(context, start, block)

/**
 * 各大环境
 */
inline val UI get() = Dispatchers.Main
inline val Default get() = Dispatchers.Default
inline val IO get() = Dispatchers.IO
inline val Unconfined get() = Dispatchers.Unconfined


val gson by lazy { Gson() }
